package com.dc.datacollect.helpers;

import com.dc.datacollect.constant.LoginCookieConstant;
import com.dc.datacollect.utils.CookieUtils;
import com.dc.datacollect.utils.DesUtils;
import com.dc.datacollect.utils.MD5Util;
import lombok.Data;

import java.util.Date;

public class RememberMeHelper {
    private static String separator = "<<s>>";
    private static Short strElementNumber = 2;
    @Data
    public static class Me {
        private String md5text;
        private String username;
    }
    public static void rememberMe(String username, String password) throws Exception {
        // （md5(username+password) <- username） <-des- timestamp
        long timestamp = System.currentTimeMillis();
        String md5Source = MD5Util.md5(username+password);
        String md5SourceConcatUsername = md5Source+separator+username;
        String encryptMD5SourceConcatUsername = DesUtils.encrypt(md5SourceConcatUsername, String.valueOf(timestamp));
        // 保存到key
        CookieUtils.addCookie(LoginCookieConstant.SOURCE_KEY,encryptMD5SourceConcatUsername,LoginCookieConstant.REMEMBER_ME_LOGIN_EFFECTIVE_DURATION);
        CookieUtils.addCookie(LoginCookieConstant.LOGIN_TIME_KEY, String.valueOf(timestamp),LoginCookieConstant.REMEMBER_ME_LOGIN_EFFECTIVE_DURATION);
    }
    public static Me verifyLogin() {
        String source = CookieUtils.getCookie(LoginCookieConstant.SOURCE_KEY);
        String loginTimestamp = CookieUtils.getCookie(LoginCookieConstant.LOGIN_TIME_KEY);
        if (source == null || loginTimestamp == null) {
            return null;
        }
        // 先看是否过期 (过去的秒 > 有效时长)
        if ( (System.currentTimeMillis() - Long.valueOf(loginTimestamp))/1000 > LoginCookieConstant.REMEMBER_ME_LOGIN_EFFECTIVE_DURATION ) {
            // 已经过期
            return null;
        }
        Me me = new Me();
        try {
            // decrypt = md5 & username
            String decrypt = DesUtils.decrypt(source, loginTimestamp);
            if (decrypt == null) {
                return null;
            }
            String[] split = decrypt.split(separator);
            if (split.length != strElementNumber) {
                // 内容无效
                return null;
            }
            me.setMd5text(split[0]);
            me.setUsername(split[1]);
            return me;
        } catch (Exception e) {
            return null;
        }
    }
    public static boolean decrypt(String username,String password,String md5text) {
        if (username == null || password == null || md5text == null) {
            return false;
        }
        String currentUserMD5text = MD5Util.md5(username + password);
        if (md5text.equals(currentUserMD5text)) {
            return true;
        }
        return false;

    }
    public static void cancelRememberMe() {
        CookieUtils.removeCookie(LoginCookieConstant.SOURCE_KEY);
        CookieUtils.removeCookie(LoginCookieConstant.LOGIN_TIME_KEY);
    }
}
